package com.szh.jexcel.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.szh.jexcel.entity.TemplateDetailEntity;
import com.szh.jexcel.entity.TemplateEntity;
import com.szh.jexcel.entity.TemplateRowEntity;
import com.szh.jexcel.mapper.TemplateDetailMapper;
import com.szh.jexcel.mapper.TemplateMapper;
import com.szh.jexcel.mapper.TemplateRowMapper;
import com.szh.jexcel.service.ExcelService;

/**
*@author szh
*@date 2022年1月14日
*/
@Service
@Transactional
public class ExcelServiceImpl implements ExcelService{
	public static final String EMPTY="EMPTY";//单元格对应属性没有值时使用该值填充
	public static final String SPLIT="/-_-/";//分隔符
	@Autowired
	private TemplateMapper templateMapper;
	@Autowired
	private TemplateDetailMapper templateDetailMapper;
	@Autowired
	private TemplateRowMapper templateRowMapper;

	@Override
	public long insert(String cells, TemplateEntity template) {
		templateMapper.insert(template);
		long tempId=template.getId();
		JSONArray cellJa=JSONArray.parseArray(cells);
		int cols=-1,rows=-1;
		//插入数据到template_detail表
		for(int i=0;i<cellJa.size();i++){
			JSONObject jo=JSONObject.parseObject(cellJa.getString(i));
			TemplateDetailEntity entity=new TemplateDetailEntity();
			entity.setTempId(tempId);
			String cellName=jo.getString("cellName");
			entity.setCellname(cellName);
			if(jo.getIntValue("datax")>cols){
				cols=jo.getIntValue("datax");
			}
			if(jo.getIntValue("datay")>rows){
				rows=jo.getIntValue("datay");
			}
			entity.setDatax(jo.getIntValue("datax"));
			entity.setDatay(jo.getIntValue("datay"));
			entity.setClasses(jo.getString("classes"));
			entity.setStyle(jo.getString("style"));
			entity.setColspan(jo.getIntValue("colspan"));
			entity.setRowspan(jo.getIntValue("rowspan"));
			entity.setDatamerged(jo.getString("datamerged"));
			
			String formula=jo.getString("formula");
			if(formula.startsWith("<input")||formula.startsWith("<div")){
				formula="";
			}
			entity.setFormula(formula);
			String innerHTML=jo.getString("innerHTML");
			entity.setText(innerHTML);
			if(innerHTML.indexOf("data-mask")!=-1){//时间
				innerHTML="data-mask";
				String times=template.getTimes();
				JSONArray time=JSONArray.parseArray(times);
				for(int j=0;j<time.size();j++){
					JSONObject t=JSONObject.parseObject(time.getString(j));
					if(t.getString("cellName").equals(cellName)){
						entity.setText(t.getString("time"));
						break;
					}
				}
			}else if(innerHTML.indexOf("jdropdown")!=-1){//下拉框
				innerHTML="jdropdown";
				String selects=template.getSelects();
				JSONArray select=JSONArray.parseArray(selects);
				for(int j=0;j<select.size();j++){
					JSONObject s=JSONObject.parseObject(select.getString(j));
					if(s.getString("cellName").equals(cellName)){
						entity.setText(s.getString("value"));
						break;
					}
				}
			}else if(innerHTML.indexOf("checkbox")!=-1){//复选框
				innerHTML="checkbox";
				String checkboxs=template.getCheckboxs();
				JSONArray checkbox=JSONArray.parseArray(checkboxs);
				for(int j=0;j<checkbox.size();j++){
					JSONObject c=JSONObject.parseObject(checkbox.getString(j));
					if(c.getString("cellName").equals(cellName)){
						entity.setText(c.getString("value"));
						break;
					}
				}
			}else{
				
			}
			entity.setInnerhtml(innerHTML);
			entity.setClientwidth(jo.getIntValue("clientWidth"));
			entity.setClientheight(jo.getIntValue("clientHeight"));
			templateDetailMapper.insert(entity);
		}
		//插入到template_row表
		cols++;
		rows++;
		for(int i=0;i<rows;i++){
			TemplateRowEntity e=new TemplateRowEntity();
			e.setTempId(tempId);
			StringBuilder cellNames=new StringBuilder();
			StringBuilder dataXs=new StringBuilder();
			StringBuilder classess=new StringBuilder();
			StringBuilder styles=new StringBuilder();
			StringBuilder colspans=new StringBuilder();
			StringBuilder rowspans=new StringBuilder();
			StringBuilder dataMergeds=new StringBuilder();
			StringBuilder innerHTMLs=new StringBuilder();
			StringBuilder clientWidths=new StringBuilder();
			StringBuilder formulas=new StringBuilder();
			int clientHeight=0;
			int dataY=-1;
			for(int j=cols*i;j<cols*(i+1);j++){
				JSONObject jo=JSONObject.parseObject(cellJa.getString(j));
				if(clientHeight==0){
					clientHeight=jo.getIntValue("clientHeight");
					dataY=jo.getIntValue("datay");
				}
				cellNames.append(jo.getString("cellName")).append(SPLIT);
				dataXs.append(jo.getString("datax")).append(SPLIT);
				classess.append(jo.getString("classes").equals("")?EMPTY:jo.getString("classes")).append(SPLIT);
				styles.append(jo.getString("style")).append(SPLIT);
				colspans.append(jo.getString("colspan").equals("")?EMPTY:jo.getString("colspan")).append(SPLIT);
				rowspans.append(jo.getString("rowspan").equals("")?EMPTY:jo.getString("rowspan")).append(SPLIT);
				dataMergeds.append(jo.getString("datamerged").equals("")?EMPTY:jo.getString("datamerged")).append(SPLIT);
				clientWidths.append(jo.getString("clientWidth")).append(SPLIT);
				String formula=jo.getString("formula").equals("")?EMPTY:jo.getString("formula");
				if(formula.startsWith("<input")||formula.startsWith("<div")){
					formula=EMPTY;
				}
				formulas.append(formula).append(SPLIT);
				String innerHTML=jo.getString("innerHTML").equals("")?EMPTY:jo.getString("innerHTML");
				if(innerHTML.indexOf("data-mask")!=-1){
					innerHTML="data-mask";
				}else if(innerHTML.indexOf("jdropdown")!=-1){
					innerHTML="jdropdown";
				}else if(innerHTML.indexOf("checkbox")!=-1){
					innerHTML="checkbox";
				}else{
					
				}
				innerHTMLs.append(innerHTML).append(SPLIT);
			}
			e.setClientheight(clientHeight);
			e.setDatay(dataY);
			e.setCellnames(cellNames.toString());
			e.setDataxs(dataXs.toString());
			e.setClassess(classess.toString());
			e.setStyles(styles.toString());
			e.setRowspans(rowspans.toString());
			e.setColspans(colspans.toString());
			e.setDatamergeds(dataMergeds.toString());
			e.setInnerhtmls(innerHTMLs.toString());
			e.setClientwidths(clientWidths.toString());
			e.setFormulas(formulas.toString());
			templateRowMapper.insert(e);
		}
		return tempId;
	}

	@Override
	public Object select(int page, int limit) {
		JSONObject jo=new JSONObject();
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("page", (page-1)*limit);
		map.put("limit", limit);
		long count=templateMapper.selectCount();
		List<TemplateEntity> list=templateMapper.selectAll(map);
		jo.put("code", 0);
		jo.put("count", count);
		jo.put("data", list);
		return jo;
	}

	@Override
	public Object getDetail(Long id) {
		JSONObject jo=new JSONObject();
		TemplateEntity template=templateMapper.selectById(id);
		jo.put("template", template);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("tempId", template.getId());
		List<TemplateRowEntity> templateRowList=templateRowMapper.selectAll(map);
		List<TemplateDetailEntity> templateDetailList=new ArrayList<TemplateDetailEntity>();
		int cols=0,rows=0;
		for(int i=0;i<templateRowList.size();i++){
			TemplateRowEntity e=templateRowList.get(i);
			String cellNames[]=e.getCellnames().split(SPLIT);
			String dataXs[]=e.getDataxs().split(SPLIT);
			String classess[]=e.getClassess().split(SPLIT);
			String styles[]=e.getStyles().split(SPLIT);
			String colspans[]=e.getColspans().split(SPLIT);
			String rowspans[]=e.getRowspans().split(SPLIT);
			String dataMergeds[]=e.getDatamergeds().split(SPLIT);
			String innerHTMLs[]=e.getInnerhtmls().split(SPLIT);
			String formulas[]=e.getFormulas().split(SPLIT);
			String clientWidths[]=e.getClientwidths().split(SPLIT);
			int dataY=e.getDatay();
			int clientHeight=e.getClientheight();
			if(i==templateRowList.size()-1){
				rows=dataY;
			}
			for(int j=0;j<cellNames.length;j++){
				TemplateDetailEntity en=new TemplateDetailEntity();
				en.setCellname(cellNames[j].equals(EMPTY)?"":cellNames[j]);
				en.setDatay(dataY);
				en.setDatax(dataXs[j].equals(EMPTY)?-1:Integer.parseInt(dataXs[j]));
				en.setClasses(classess[j].equals(EMPTY)?"":classess[j]);
				en.setStyle(styles[j].equals(EMPTY)?"":styles[j]);
				en.setColspan(colspans[j].equals(EMPTY)?0:Integer.parseInt(colspans[j]));
				en.setRowspan(rowspans[j].equals(EMPTY)?0:Integer.parseInt(rowspans[j]));
				en.setDatamerged(dataMergeds[j].equals(EMPTY)?"":dataMergeds[j]);
				en.setClientwidth(clientWidths[j].equals(EMPTY)?0:Integer.parseInt(clientWidths[j]));
				en.setClientheight(clientHeight);
				en.setInnerhtml(innerHTMLs[j].equals(EMPTY)?"":innerHTMLs[j]);
				en.setFormula(formulas[j].equals(EMPTY)?"":formulas[j]);
				templateDetailList.add(en);
			}
		}
		
		if(templateRowList.size()>0){
			cols=templateRowList.get(0).getDataxs().split(SPLIT).length;
		}
		jo.put("detail", templateDetailList);
		jo.put("rows", rows+1);
		jo.put("cols", cols);
		return jo;
	}

	@Override
	public long update(String cells, TemplateEntity template) {
		int record=templateMapper.update(template);
		long tempId=template.getId();
		templateDetailMapper.deleteByTempId(tempId);
		templateRowMapper.deleteByTempId(tempId);
		
		JSONArray cellJa=JSONArray.parseArray(cells);
		int cols=-1,rows=-1;
		//插入数据到template_detail表
		for(int i=0;i<cellJa.size();i++){
			JSONObject jo=JSONObject.parseObject(cellJa.getString(i));
			TemplateDetailEntity entity=new TemplateDetailEntity();
			entity.setTempId(tempId);
			String cellName=jo.getString("cellName");
			entity.setCellname(cellName);
			if(jo.getIntValue("datax")>cols){
				cols=jo.getIntValue("datax");
			}
			if(jo.getIntValue("datay")>rows){
				rows=jo.getIntValue("datay");
			}
			entity.setDatax(jo.getIntValue("datax"));
			entity.setDatay(jo.getIntValue("datay"));
			entity.setClasses(jo.getString("classes"));
			entity.setStyle(jo.getString("style"));
			entity.setColspan(jo.getIntValue("colspan"));
			entity.setRowspan(jo.getIntValue("rowspan"));
			entity.setDatamerged(jo.getString("datamerged"));
			
			String formula=jo.getString("formula");
			if(formula.startsWith("<input")||formula.startsWith("<div")){
				formula="";
			}
			entity.setFormula(formula);
			String innerHTML=jo.getString("innerHTML");
			entity.setText(innerHTML);
			if(innerHTML.indexOf("data-mask")!=-1){//时间
				innerHTML="data-mask";
				String times=template.getTimes();
				JSONArray time=JSONArray.parseArray(times);
				for(int j=0;j<time.size();j++){
					JSONObject t=JSONObject.parseObject(time.getString(j));
					if(t.getString("cellName").equals(cellName)){
						entity.setText(t.getString("time"));
						break;
					}
				}
			}else if(innerHTML.indexOf("jdropdown")!=-1){//下拉框
				innerHTML="jdropdown";
				String selects=template.getSelects();
				JSONArray select=JSONArray.parseArray(selects);
				for(int j=0;j<select.size();j++){
					JSONObject s=JSONObject.parseObject(select.getString(j));
					if(s.getString("cellName").equals(cellName)){
						entity.setText(s.getString("value"));
						break;
					}
				}
			}else if(innerHTML.indexOf("checkbox")!=-1){//复选框
				innerHTML="checkbox";
				String checkboxs=template.getCheckboxs();
				JSONArray checkbox=JSONArray.parseArray(checkboxs);
				for(int j=0;j<checkbox.size();j++){
					JSONObject c=JSONObject.parseObject(checkbox.getString(j));
					if(c.getString("cellName").equals(cellName)){
						entity.setText(c.getString("value"));
						break;
					}
				}
			}else{
				
			}
			entity.setInnerhtml(innerHTML);
			entity.setClientwidth(jo.getIntValue("clientWidth"));
			entity.setClientheight(jo.getIntValue("clientHeight"));
			templateDetailMapper.insert(entity);
		}
		//插入到template_row表
		cols++;
		rows++;
		for(int i=0;i<rows;i++){
			TemplateRowEntity e=new TemplateRowEntity();
			e.setTempId(tempId);
			StringBuilder cellNames=new StringBuilder();
			StringBuilder dataXs=new StringBuilder();
			StringBuilder classess=new StringBuilder();
			StringBuilder styles=new StringBuilder();
			StringBuilder colspans=new StringBuilder();
			StringBuilder rowspans=new StringBuilder();
			StringBuilder dataMergeds=new StringBuilder();
			StringBuilder innerHTMLs=new StringBuilder();
			StringBuilder clientWidths=new StringBuilder();
			StringBuilder formulas=new StringBuilder();
			int clientHeight=0;
			int dataY=-1;
			for(int j=cols*i;j<cols*(i+1);j++){
				JSONObject jo=JSONObject.parseObject(cellJa.getString(j));
				if(clientHeight==0){
					clientHeight=jo.getIntValue("clientHeight");
					dataY=jo.getIntValue("datay");
				}
				cellNames.append(jo.getString("cellName")).append(SPLIT);
				dataXs.append(jo.getString("datax")).append(SPLIT);
				classess.append(jo.getString("classes").equals("")?EMPTY:jo.getString("classes")).append(SPLIT);
				styles.append(jo.getString("style")).append(SPLIT);
				colspans.append(jo.getString("colspan").equals("")?EMPTY:jo.getString("colspan")).append(SPLIT);
				rowspans.append(jo.getString("rowspan").equals("")?EMPTY:jo.getString("rowspan")).append(SPLIT);
				dataMergeds.append(jo.getString("datamerged").equals("")?EMPTY:jo.getString("datamerged")).append(SPLIT);
				clientWidths.append(jo.getString("clientWidth")).append(SPLIT);
				String formula=jo.getString("formula").equals("")?EMPTY:jo.getString("formula");
				if(formula.startsWith("<input")||formula.startsWith("<div")){
					formula=EMPTY;
				}
				formulas.append(formula).append(SPLIT);
				String innerHTML=jo.getString("innerHTML").equals("")?EMPTY:jo.getString("innerHTML");
				if(innerHTML.indexOf("data-mask")!=-1){
					innerHTML="data-mask";
				}else if(innerHTML.indexOf("jdropdown")!=-1){
					innerHTML="jdropdown";
				}else if(innerHTML.indexOf("checkbox")!=-1){
					innerHTML="checkbox";
				}else{
					
				}
				innerHTMLs.append(innerHTML).append(SPLIT);
			}
			e.setClientheight(clientHeight);
			e.setDatay(dataY);
			e.setCellnames(cellNames.toString());
			e.setDataxs(dataXs.toString());
			e.setClassess(classess.toString());
			e.setStyles(styles.toString());
			e.setRowspans(rowspans.toString());
			e.setColspans(colspans.toString());
			e.setDatamergeds(dataMergeds.toString());
			e.setInnerhtmls(innerHTMLs.toString());
			e.setClientwidths(clientWidths.toString());
			e.setFormulas(formulas.toString());
			templateRowMapper.insert(e);
		}
		return record;
	}

	@Override
	public long delete(TemplateEntity excel) {
		long tempId=excel.getId();
		int record=templateMapper.deleteById(tempId);
		templateDetailMapper.deleteByTempId(tempId);
		templateRowMapper.deleteByTempId(tempId);
		return record;
	}

}
